package com.zmm.study.mes.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.zmm.study.mes.entity.system.SysUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.shiro.SecurityUtils;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * description
 * name SpMetaObjectHandler
 *
 * @author Zebulon
 * @date by 2022-05-05 20:33:55
 */
@Slf4j
@Component
public class SpMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        log.info("start insert fill ...");
        this.setInsertData(metaObject);
        this.setUpdateData(metaObject);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        log.info("start update fill ...");
        this.setUpdateData(metaObject);
    }

    private void setInsertData(MetaObject metaObject) {
        SysUser sysUser = (SysUser) SecurityUtils.getSubject().getPrincipal();
        this.setFieldValByName("createUserName", sysUser.getUsername(), metaObject);
        this.setFieldValByName("createTime", LocalDateTime.now(), metaObject);
    }

    private void setUpdateData(MetaObject metaObject) {
        SysUser sysUser = (SysUser) SecurityUtils.getSubject().getPrincipal();
        this.setFieldValByName("updateUserName", sysUser.getUsername(), metaObject);
        this.setFieldValByName("updateTime", LocalDateTime.now(), metaObject);
    }
}
